import React, { Component } from 'react'
import {Input,Button} from 'antd'
import { rule } from '_postcss@7.0.18@postcss';

//创建一个高阶组件：扩展现有的表单，事件处理，数据收集，效验
function kFormCreate(Comp){
  return class extends Component{ 
    constructor(props){
      super(props);
      this.options={};
      this.state={};
    }
    handleChange=(e)=>{
      const {name,value}=e.target;
      this.setState({[name]:value},()=>{
        this.validateField(name)
      })
    }
    validateField = field => {
      const rules=this.options[field].rules;
      const ret = ! rules.some(rule=>{
        if(rule.required){
          console.log(rule)
          if(!this.state[field]){
            //校验失败
            this.setState({
              [field+'Message']:rule.message
            })
            return true
          }else{
            if(this.state[field].length<rule.min || this.state[field].length>rule.max){
                //校验失败
                this.setState({
                  [field+'Message']:rule.message
                })
                return true
            }
          }
        }
      })
      if(ret){
        this.setState({
          [field+'Message']:''
        })
      }
      return ret;
    }
    validate=(cd)=>{
      const rets=Object.keys(this.options).map(field=>
        this.validateField(field)
      )
      // eslint-disable-next-line eqeqeq
      const ret=rets.every(v => v == true);
      cd(ret,this.state)
    }
    //创建Input包装器
    getFieldDec=(field,option)=>{
      //保存当前输入项配置
      this.options[field] = option;
      return InputComp=>(
        <div>
          {React.cloneElement(InputComp,{
            name:field,
            value:this.state[field] || '',
            onChange:this.handleChange
          })}
          {this.state[field+'Message'] && (
            <p style={{color:'red'}}>{this.state[field+'Message']}</p>
          )}
        </div>
      )
    }
    render(){
      return <Comp getFieldDec={this.getFieldDec} validate={this.validate}/>
    }
  }
}

@kFormCreate
class KForm extends Component {
  onSubmit=()=>{
    //效验所有项
    this.props.validate((isValid,data)=>{
      if(isValid){
        console.log('成功')
      }else{
        console.log('失败')
      }
    })
  }
  render() {
    const {getFieldDec}=this.props;
    return (
      <div>
        {getFieldDec('uname',{
          rules:[{required:true,message:'用户名必填'},{required:true, min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'} ]
        })(<Input/>)}
        {getFieldDec('pwd',{
          rules:[{required:true,message:'密码必填'}]
        })(<Input type="password"/>)}
        <Button onClick={this.onSubmit}>登录</Button>
      </div>
    )
  }
}

export default KForm;
